package com.youtui.common.util;

import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Component
public class ExcelImportUtil {

	// �ж��ļ�����
	public Workbook getWorkBook(String filePath, InputStream fis) throws Exception {
		// 
		Workbook workBook = null;
		if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
			throw new Exception("excel 文件格式错误");
		}
		if (filePath.endsWith(".xls")) {
			// 2003 
			workBook = new HSSFWorkbook(fis, true);
		}
		if (filePath.endsWith(".xlsx")) {
			// 2007 
			workBook = new XSSFWorkbook(fis);
		}
		return workBook;
	}

	public String[] getExcelRow(Row row, int columnNum) {
		String[] s;
		StringBuilder builder = new StringBuilder();
		for (int x = 0; x < columnNum; x++) {
			// 
			Cell cell = row.getCell(x);
			builder.append(getStringCellValue(cell) + ",");
		}
		s = builder.toString().split(",");
		return s;
	}

	// 
	public String getStringCellValue(Cell cell) {
		StringBuilder sb = new StringBuilder();
		switch (cell.getCellType()) {
		// 
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				sb.append(cell.getDateCellValue());
			} else {
				sb.append(cell.getNumericCellValue());
			}
			break;
		// �ַ�
		case Cell.CELL_TYPE_STRING:
			sb.append(cell.getStringCellValue());
			break;
		// ����
		case Cell.CELL_TYPE_BOOLEAN:
			sb.append(cell.getBooleanCellValue());
			break;
		// ��ʽ
		case Cell.CELL_TYPE_FORMULA:
			sb.append(cell.getCellFormula());
			break;
		// ��ֵ
		case Cell.CELL_TYPE_BLANK:
			sb.append("");
			break;
		// ����
		case Cell.CELL_TYPE_ERROR:
			sb.append("");
			break;
		default:
			sb.append("");
			break;
		}
		return sb.toString();
	}
}
